<template>
  <div class="soil-monitor">
    <div class="section-title">
      <el-icon><Monitor /></el-icon>
      土壤监测数据
    </div>
    <div class="monitor-grid">
      <el-card v-for="sensor in sensors" :key="sensor.type" class="monitor-item" shadow="never">
        <div class="monitor-title">
          <el-icon><component :is="sensor.icon" /></el-icon>
          {{ sensor.name }}
        </div>
        <div class="monitor-value">
          {{ sensor.value }} {{ sensor.unit }}
        </div>
      </el-card>
    </div>
    <div class="section-title" style="margin-top: 20px;">
      <el-icon><DataLine /></el-icon>
      土壤数据趋势
    </div>
    <el-card class="chart-container" shadow="never">
      <div ref="trendChart" class="trend-chart"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { Monitor, DataLine } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getSoilTemperatureData,
  getPhData,
  getPhosphorusData,
  getPotassiumData,
  getLightData,
  collectSoilTemperatureData,
  collectPhData,
  collectPhosphorusData,
  collectPotassiumData,
  collectLightData
} from '@/api'

const props = defineProps({
  greenhouseId: {
    type: String,
    required: true
  }
})

const trendChart = ref(null)
let chart = null

const sensors = reactive([
  { type: 'temperature', name: '土壤温度', value: 0, unit: '°C', icon: 'Thermometer' },
  { type: 'ph', name: '土壤pH值', value: 0, unit: '', icon: 'WaterMeter' },
  { type: 'phosphorus', name: '磷含量', value: 0, unit: 'mg/kg', icon: 'Histogram' },
  { type: 'potassium', name: '钾含量', value: 0, unit: 'mg/kg', icon: 'Histogram' },
  { type: 'light', name: '光照强度', value: 0, unit: 'lux', icon: 'Sunny' }
])

// 格式化日期为时间戳
const formatDate = (date) => {
  return Math.floor(date.getTime())
}

// 获取实时数据
const fetchRealTimeData = async () => {
  try {
    const now = new Date()
    const fiveMinutesAgo = new Date(now - 5 * 60 * 1000)
    
    const [tempData, phData, phosphorusData, potassiumData, lightData] = await Promise.all([
      getSoilTemperatureData(formatDate(fiveMinutesAgo), formatDate(now)),
      getPhData(formatDate(fiveMinutesAgo), formatDate(now)),
      getPhosphorusData(formatDate(fiveMinutesAgo), formatDate(now)),
      getPotassiumData(formatDate(fiveMinutesAgo), formatDate(now)),
      getLightData(formatDate(fiveMinutesAgo), formatDate(now))
    ])
    
    // 更新传感器数据
    updateSensorValue('temperature', tempData)
    updateSensorValue('ph', phData)
    updateSensorValue('phosphorus', phosphorusData)
    updateSensorValue('potassium', potassiumData)
    updateSensorValue('light', lightData)
    
  } catch (error) {
    console.error('获取实时数据失败:', error)
  }
}

// 更新传感器值
const updateSensorValue = (type, data) => {
  if (data && data.length > 0) {
    const sensor = sensors.find(s => s.type === type)
    if (sensor) {
      sensor.value = data[data.length - 1].value
    }
  }
}

// 获取历史数据
const fetchHistoryData = async () => {
  try {
    const endTime = new Date()
    const startTime = new Date(endTime - 24 * 60 * 60 * 1000)
    
    const [tempData, phData, phosphorusData, potassiumData, lightData] = await Promise.all([
      getSoilTemperatureData(formatDate(startTime), formatDate(endTime)),
      getPhData(formatDate(startTime), formatDate(endTime)),
      getPhosphorusData(formatDate(startTime), formatDate(endTime)),
      getPotassiumData(formatDate(startTime), formatDate(endTime)),
      getLightData(formatDate(startTime), formatDate(endTime))
    ])
    
    updateTrendChart(tempData, phData, phosphorusData, potassiumData, lightData)
  } catch (error) {
    console.error('获取历史数据失败:', error)
  }
}

// 初始化趋势图
const initTrendChart = () => {
  if (!trendChart.value) return
  
  chart = echarts.init(trendChart.value)
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['温度', 'pH值', '磷含量', '钾含量', '光照'],
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      }
    },
    series: [
      {
        name: '温度',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: 'pH值',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '磷含量',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '钾含量',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '光照',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  }
  
  chart.setOption(option)
}

// 更新趋势图数据
const updateTrendChart = (tempData, phData, phosphorusData, potassiumData, lightData) => {
  if (!chart) return
  
  const formatData = (data) => {
    return data.map(item => [new Date(item.timestamp).getTime(), item.value])
  }
  
  chart.setOption({
    series: [
      { data: formatData(tempData) },
      { data: formatData(phData) },
      { data: formatData(phosphorusData) },
      { data: formatData(potassiumData) },
      { data: formatData(lightData) }
    ]
  })
}

// 手动触发数据采集
const collectData = async () => {
  try {
    await Promise.all([
      collectSoilTemperatureData(),
      collectPhData(),
      collectPhosphorusData(),
      collectPotassiumData(),
      collectLightData()
    ])
    fetchRealTimeData()
  } catch (error) {
    console.error('数据采集失败:', error)
  }
}

onMounted(() => {
  initTrendChart()
  fetchRealTimeData()
  fetchHistoryData()
  
  // 每5分钟更新一次实时数据
  const realTimeTimer = setInterval(fetchRealTimeData, 5 * 60 * 1000)
  // 每小时更新一次历史数据
  const historyTimer = setInterval(fetchHistoryData, 60 * 60 * 1000)
  
  onUnmounted(() => {
    clearInterval(realTimeTimer)
    clearInterval(historyTimer)
    if (chart) {
      chart.dispose()
      chart = null
    }
  })
})
</script>

<style scoped>
.soil-monitor {
  background: rgba(0, 21, 41, 0.7);
  border: 1px solid rgba(0, 222, 255, 0.3);
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  box-sizing: border-box;
  min-height: 400px;
  height: 100%;
}

.section-title {
  color: #00deff;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  text-shadow: 0 0 10px rgba(0, 222, 255, 0.3);
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.monitor-item {
  background: rgba(0, 21, 41, 0.5) !important;
  border: 1px solid rgba(0, 222, 255, 0.2) !important;
  border-radius: 6px !important;
  padding: 12px !important;
  transition: all 0.3s ease;
}

.monitor-item:hover {
  border-color: rgba(0, 222, 255, 0.4) !important;
  box-shadow: 0 0 15px rgba(0, 222, 255, 0.1);
}

.monitor-title {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.monitor-title .el-icon {
  color: #00deff;
}

.monitor-value {
  color: #00deff;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.chart-container {
  flex: 1;
  background: rgba(41, 0, 25, 0.5) !important;
  border: 1px solid rgba(0, 222, 255, 0.2) !important;
  border-radius: 6px !important;
  min-height: 0;
  transition: all 0.3s ease;
}

.chart-container:hover {
  border-color: rgba(0, 222, 255, 0.4) !important;
  box-shadow: 0 0 15px rgba(0, 222, 255, 0.1);
}

:deep(.chart-container .el-card__body) {
  height: 100%;
  padding: 12px;
  display: flex;
}

.trend-chart {
  flex: 1;
  width: 100%;
  min-height: 200px;
}
</style> 